package win.larryzeal.nio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * traditional IO model (single) - socket programming
 * <p>
 * Created by LarryZeal on 2017/9/18.
 */
public class TraditionalSocketDemo {
    public static void main(String[] args) throws IOException{
//        single();
        multiple();
    }

    /**
     * FIXME 这段代码，实际上同时只能接收一个客户端请求，因为是阻塞式。
     *
     * @throws IOException
     */
    private static void single() throws IOException{
        ServerSocket serverSocket = new ServerSocket(6379);
        System.out.println("Server started..");

        while(true){
            Socket socket = serverSocket.accept(); // block point
            System.out.println(LocalDateTime.now() + ": socket established!");

            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while(true){
                int size = inputStream.read(bytes); // block point
                if(size != -1){
                    String info = new String(bytes, 0, size, "gbk");
                    System.out.println("got data: " + info);
                } else{
                    System.out.println("quit...");
                    break;
                }
            }
        }
    }

    /**
     * 可以同时接受多个客户端。
     * 缺点就是，①线程数量受系统资源限制；②线程多了会导致严重的资源浪费，如线程切换等操作带来的时间损失。
     *
     * @throws IOException
     */
    private static void multiple() throws IOException{
        ExecutorService executorService = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6379);
        System.out.println("Server started..");

        while(true){
            Socket socket = serverSocket.accept(); // block point
            System.out.println(LocalDateTime.now() + ": socket established!");

            executorService.execute(() -> {
                InputStream inputStream = null;
                try{
                    inputStream = socket.getInputStream();
                    byte[] bytes = new byte[1024];
                    while(true){
                        int size = inputStream.read(bytes); // block point
                        if(size != -1){
                            String info = new String(bytes, 0, size, "gbk");
                            System.out.println("got data: " + info);
                        } else{
                            System.out.println("quit...");
                            break;
                        }
                    }
                } catch(IOException e){
                    e.printStackTrace();
                }
            });
        }
    }
}
